package com.adu.music.spider;

import com.adu.music.api.MusicApi;
import com.adu.music.bean.ArtistCategory;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author duchuanchuan
 * @date 2017/1/1
 */
public class ArtistSpider extends AbstractSpider {

    private final List<ArtistCategory> categories = new ArrayList<>();
    private int index = 0;

    public ArtistSpider() {
        initCategories();
        this.setQueueCapacity(50);
    }

    private void initCategories() {
        categories.add(new ArtistCategory(1001, "华语男歌手"));
        categories.add(new ArtistCategory(1002, "华语女歌手"));
        categories.add(new ArtistCategory(1003, "华语组合/乐队"));

        categories.add(new ArtistCategory(2001, "欧美男歌手"));
        categories.add(new ArtistCategory(2002, "欧美女歌手"));
        categories.add(new ArtistCategory(2003, "欧美组合/乐队"));

        categories.add(new ArtistCategory(6001, "日本男歌手"));
        categories.add(new ArtistCategory(6002, "日本女歌手"));
        categories.add(new ArtistCategory(6003, "日本组合/乐队"));

        categories.add(new ArtistCategory(7001, "韩国男歌手"));
        categories.add(new ArtistCategory(7002, "韩国女歌手"));
        categories.add(new ArtistCategory(7003, "韩国组合/乐队"));

        categories.add(new ArtistCategory(4001, "其他男歌手"));
        categories.add(new ArtistCategory(4001, "其他女歌手"));
        categories.add(new ArtistCategory(4001, "其他组合/乐队"));
    }

    @Override
    protected void initTaskQueue() {
        ArtistCategory category = categories.get(index);
        for (int i = 65; i <= 90; i++) {
            category.setInitial(i);
            putTaskToQueue(category);
        }
        index++;
    }

    @Override
    protected void produceTask() {
        while (index < categories.size()) {
            ArtistCategory category = categories.get(index);
            for (int i = 65; i <= 90; i++) {
                category.setInitial(i);
                // 加入任务队列
                this.putTaskToQueue(category);
            }
            index++;
        }
    }

    @Override
    protected void consumeTask(Object task) {
        ArtistCategory category = (ArtistCategory) task;
        List<Map<String, Object>> maps = MusicApi.crawlArtist(category);
        if (maps.isEmpty()) {
            logger.info("种类,ID:{},名称:{}, 字母:{}, ERROR", category.getId(), category.getName(), category.getInitial());
            return;
        }
        final String sql = "insert into artist(id,name,category_id,category_name) values(:id,:name,:category_id,:category_name)";
        int[] ints = asyncNamedParameterJdbcTemplate.batchUpdate(sql, maps.toArray(new Map[0]));
        logger.info("插入了{}条数据", ints.length);
    }
}
